package net.csdn.business.common.config.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import net.csdn.business.common.annotation.JsonCustomFormat;
import net.csdn.business.common.utils.CommonUtil;

import java.io.IOException;
import java.util.Objects;

/**
 * @author likun
 * @date 2022/7/20 14:14
 */
public class JsonCustomFormatSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private String format = "yyyy-MM-dd HH:mm:ss";
    private String inputFormat = "yyyy-MM-dd'T'HH:mm:ss+08:00";

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            if (Objects.equals(beanProperty.getType().getRawClass(), String.class)) {
                JsonCustomFormat jsonCustomFormat = beanProperty.getAnnotation((JsonCustomFormat.class));
                if (jsonCustomFormat == null) {
                    jsonCustomFormat = beanProperty.getContextAnnotation(JsonCustomFormat.class);
                }
                JsonCustomFormatSerializer jsonCustomFormatSerializer = new JsonCustomFormatSerializer();
                if (jsonCustomFormat != null) {
                    jsonCustomFormatSerializer.format = jsonCustomFormat.pattern();
                    jsonCustomFormatSerializer.inputFormat = jsonCustomFormat.inputPattern();
                }
                return jsonCustomFormatSerializer;
            }
            return serializerProvider.findValueSerializer(beanProperty.getType(), beanProperty);
        }
        return serializerProvider.findNullValueSerializer(null);
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        gen.writeString(CommonUtil.formatStringDate(value, inputFormat, format));
    }
}